import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/home_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/address_info.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/model/toast/toast.dart';

enum ChooseType {
  addressType,
  yearsType,
  plListType
}

class HomeSelAddressPage extends StatefulWidget {
  final Function? selAddress;
  final ChooseType? chooseType;
  const HomeSelAddressPage({Key? key, this.selAddress, this.chooseType=ChooseType.addressType,}) : super(key: key);

  @override
  _HomeSelAddressPageState createState() => _HomeSelAddressPageState();
}

class _HomeSelAddressPageState extends State<HomeSelAddressPage> {

  FixedExtentScrollController cityController = FixedExtentScrollController();
  FixedExtentScrollController yearController = FixedExtentScrollController();
  FixedExtentScrollController disttroller = FixedExtentScrollController();
  List provices = [];
  List cityies = [];
  List districts = [];
  int proIndex = 0;
  int cityIndex = 0;
  int distIndex = 0;

  List plList = [];

  String? adCode;
  String? name;
  String? cityName;
  String? pname;
  List<String>? years = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.chooseType==ChooseType.addressType){
      getAddress();
    }
    if(widget.chooseType==ChooseType.yearsType){
      DateTime today = new DateTime.now();
      int nowYear = today.year;
      for(var i=nowYear-30;i<2099;i++){
        years!.add('$i');
      }
      name = years![0];
      adCode = years![0];
    }
    if(widget.chooseType==ChooseType.plListType){
      getTypes();
    }
    WidgetsBinding.instance.addPostFrameCallback((callback)async {
      if(widget.chooseType==ChooseType.yearsType){
        name = years![30];
        adCode = years![30];
        yearController.animateToItem(30, duration: const Duration(milliseconds: 10), curve: Curves.linear);
      }
    });
  }

  getTypes()async{
    plList = await AddressInfo.getPlList();
    if(plList.isNotEmpty){
      name = plList[0]['name'];
      adCode = '${plList[0]['id']}';
    }
    if(mounted){setState(() {});}
  }

  getAddress()async{
    Map address = await AddressInfo.getAddress();
    provices = address['districts'][0]['districts']??[];
    provices.sort(((a, b) => a['adcode'].compareTo(b['adcode'])));
    cityies = provices[proIndex]['districts'];
    cityies.sort(((a, b) => a['adcode'].compareTo(b['adcode'])));
    districts = cityies[cityIndex]['districts']??[];
    print('区====='+districts.toString());
    setState(() {
      pname = '${provices[proIndex]['name']}';
      cityName = '${cityies[cityIndex]['name']}';
      name = '${districts[distIndex]['name']}';
      adCode = districts[distIndex]['adcode']??cityies[cityIndex]['adcode']??provices[proIndex]['adcode'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){

      },
      child: Container(
        color: Colors.transparent,
        child: Column(
          children: [
            Expanded(child: GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
              },
              child: Container(color: Colors.transparent,),
            )),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.w)
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    padding: EdgeInsets.only(
                      top: 55.w,
                      left: 28.w,
                      right: 28.w,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(20.sp),
                        topRight: Radius.circular(20.sp),
                      ),
                    ),
                    child: Container(
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.only(bottom: 74.w),
                            child: Row(
                              children: [
                                Container(
                                  child: Text(
                                   widget.chooseType==ChooseType.addressType? "请选择地址":
                                   widget.chooseType==ChooseType.yearsType?"请选择年份":
                                   widget.chooseType==ChooseType.plListType?"请选择品类":"请选择",
                                    style: TextStyle(
                                      color: Color(0xFF333333),
                                      fontSize: 32.sp,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                                Expanded(child: Container()),
                                GestureDetector(
                                  onTap: () async {
                                    SmartDialog.dismiss();
                                  },
                                  child: Container(
                                    child: Text(
                                      '取消',
                                      style: TextStyle(
                                        color: Color(0xFF999999),
                                        fontSize: 30.sp,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Visibility(child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Container(
                        width: 0.3.sw,
                        height: 400.w,
                        child: CupertinoPicker(
                          magnification: 1.2,
                          selectionOverlay: Container(
                            decoration: BoxDecoration(
                                border: Border(top: BorderSide(color: bgColor,width: 1),bottom: BorderSide(color: bgColor,width: 1))
                            ),
                          ),
                          itemExtent: 90.w, //行高
                          onSelectedItemChanged: (value) {
                            proIndex = value;
                            cityController.animateTo(0, duration: const Duration(microseconds: 100), curve: Curves.linear);
                            cityIndex=0;
                            cityies=[];
                            cityName = '';
                            districts = [];
                            distIndex = 0;
                            name = '';
                            setState(() {
                              pname = '${provices[proIndex]['name']}';
                              cityies = provices[proIndex]['districts']??[];
                              adCode = '${provices[proIndex]['adcode']}';
                              if(cityies.isNotEmpty){
                                cityName = '${cityies[cityIndex]['name']}';
                                adCode = '${cityies[cityIndex]['adcode']}';
                                districts = cityies[cityIndex]['districts']??[];
                                if(districts.isNotEmpty){
                                  name = '${districts[distIndex]['name']}';
                                  adCode = '${districts[distIndex]['adcode']}';
                                }
                              }
                              });
                          },
                          children: provices.map((e){
                            return Container(
                              child: Text(e['name'],style: TextStyle(
                                  color: e['name'] == pname?defaultBarColor: Colors.black,
                                  fontSize: 30.sp,
                                  fontWeight: FontWeight.w500
                              ),),
                              height: 90.w,
                              alignment: Alignment.center,
                            );
                          }).toList(),
                        ),
                      ),
                      Container(
                        width: 0.3.sw,
                        height: 400.w,
                        child: CupertinoPicker(
                            scrollController: cityController,
                            magnification:1.2,
                            selectionOverlay: Container(
                              decoration: BoxDecoration(
                                  border: Border(top: BorderSide(color: bgColor,width: 1),bottom: BorderSide(color: bgColor,width: 1))
                              ),
                            ),
                            itemExtent: 90.w, //行高
                            onSelectedItemChanged: (value) {
                              cityIndex = value;
                              disttroller.animateTo(0, duration: const Duration(microseconds: 100), curve: Curves.linear);
                              districts = [];
                              distIndex = 0;
                              name = '';
                              setState(() {
                                cityName = '${cityies[cityIndex]['name']}';
                                adCode = '${cityies[cityIndex]['adcode']}';
                                districts = cityies[cityIndex]['districts']??[];
                                if(districts.isNotEmpty){
                                  name = '${districts[distIndex]['name']}';
                                  adCode = districts[distIndex]['adcode'];
                                }
                              });
                            },
                            children: cityies.map((e){
                              return Container(
                                child: Text(e['name'],style: TextStyle(
                                    color:e['name']==cityName?defaultBarColor: Colors.black,
                                    fontSize: 30.sp,
                                    fontWeight: FontWeight.w500
                                ),),
                                height: 90.w,
                                alignment: Alignment.center,
                              );
                            }).toList()
                        ),
                      ),
                      Container(
                        width: 0.3.sw,
                        height: 400.w,
                        child: CupertinoPicker(
                            scrollController: disttroller,
                            magnification:1.2,
                            selectionOverlay: Container(
                              decoration: BoxDecoration(
                                  border: Border(top: BorderSide(color: bgColor,width: 1),bottom: BorderSide(color: bgColor,width: 1))
                              ),
                            ),
                            itemExtent: 90.w, //行高
                            onSelectedItemChanged: (value) {
                              distIndex = value;
                              setState(() {
                                name = '${districts[distIndex]['name']}';
                                adCode = districts[distIndex]['adcode']??cityies[cityIndex]['adcode']??provices[proIndex]['adcode'];
                              });
                            },
                            children: districts.map((e){
                              return Container(
                                child: Text(e['name'],style: TextStyle(
                                    color:e['name']==name?defaultBarColor: Colors.black,
                                    fontSize: 30.sp,
                                    fontWeight: FontWeight.w500
                                ),),
                                height: 90.w,
                                alignment: Alignment.center,
                              );
                            }).toList()
                        ),
                      ),
                    ],
                  ),visible: widget.chooseType==ChooseType.addressType,),
                  Visibility(child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Container(
                        width: 1.sw,
                        height: 400.w,
                        child: CupertinoPicker(
                          scrollController: yearController,
                          magnification: 1.2,
                          selectionOverlay: Container(
                            decoration: BoxDecoration(
                                border: Border(top: BorderSide(color: bgColor,width: 1),bottom: BorderSide(color: bgColor,width: 1))
                            ),
                          ),
                          itemExtent: 90.w, //行高
                          onSelectedItemChanged: (value) {
                            setState(() {
                              name = years?[value];
                              adCode = years?[value];
                            });
                          },
                          children: years!.map((e){
                            return Container(
                              child: Text(e,style: TextStyle(
                                  color:e==name?defaultBarColor: Colors.black,
                                  fontSize: 30.sp,
                                  fontWeight: FontWeight.w500
                              ),),
                              height: 90.w,
                              alignment: Alignment.center,
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),visible: widget.chooseType==ChooseType.yearsType,),
                  Visibility(child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Container(
                        width: 1.sw,
                        height: 400.w,
                        child: CupertinoPicker(
                          magnification: 1.2,
                          selectionOverlay: Container(
                            decoration: BoxDecoration(
                                border: Border(top: BorderSide(color: bgColor,width: 1),bottom: BorderSide(color: bgColor,width: 1))
                            ),
                          ),
                          itemExtent: 90.w, //行高
                          onSelectedItemChanged: (value) {
                            setState(() {
                              name = plList[value]['name'];
                              adCode = '${plList[value]['id']}';
                            });
                          },
                          children: plList.map((e){
                            return Container(
                              child: Text(e['name'],style: TextStyle(
                                  color: e['name']==name?defaultBarColor: Colors.black,
                                  fontSize: 30.sp,
                                  fontWeight: FontWeight.w500
                              ),),
                              height: 90.w,
                              alignment: Alignment.center,
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),visible: widget.chooseType==ChooseType.plListType,),
                  Container(
                    color: Colors.white,
                    padding: EdgeInsets.only(
                        bottom: MediaQuery.of(context).padding.bottom + 30.w),
                    child: GestureDetector(
                      onTap: () async {
                        if(widget.selAddress!=null){
                          widget.selAddress!(pname ,cityName, name,adCode);
                        }
                        SmartDialog.dismiss();
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(color: Color(0xFFF76E1E), width: 1.sp),
                          borderRadius: BorderRadius.all(Radius.circular(40.sp)),
                        ),
                        width: 690.w,
                        height: 80.w,
                        child: Center(
                          child: Text(
                            "完成",
                            style: TextStyle(
                              color: Color(0xFFF76E1E),
                              fontSize: 30.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

}
